const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require("koa2-cors");

const index = require('./routes/index')
const imgvideo = require('./routes/imgvideo')
const backIndex = require('./routes/backIndex')
const users = require('./routes/users')
const creator = require('./routes/creator')
const forum = require('./routes/forum')
const message = require('./routes/message')
const feedback = require('./routes/feedback')
const person = require('./routes/person')
const backFeedback = require('./routes/backFeedback')
const subscriber = require('./routes/subscriber')
const manager = require('./routes/manager')
const works = require('./routes/works')


const db = require('./db/dbmanager')
const { koaBody } = require('koa-body');
const path = require('path')
// error handler
onerror(app)

// middlewares
app.use(cors());

// app.use(bodyparser({
//   enableTypes: ['json', 'form', 'text']
// }))
app.use(koaBody(
  {
    multipart: true, // 支持文件上传
    text: true,
    strict: false,
    formidable: {
      uploadDir: path.join(__dirname, '/public/images/'), // 设置文件上传目录
      keepExtensions: true,    // 保持文件的后缀
      maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
      onFileBegin: (name, file) => { // 文件上传前的设置
        // console.log(`name: ${name}`);
        // console.log(file);
        // const dirName = file.newFilename
        // const dir = path.join(__dirname, `public/upload`);
        // // 覆盖文件存放的完整路径(保留原始名称)
        // file.filepath = `${dir}\\${file.originalFilename}`;
      },
    }
  }
));
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(async (ctx, next) => {
  ctx.db = db;
  await next()
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(imgvideo.routes(), imgvideo.allowedMethods())
app.use(backIndex.routes(), backIndex.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(creator.routes(), creator.allowedMethods())
app.use(forum.routes(), forum.allowedMethods())
app.use(message.routes(), message.allowedMethods())
app.use(feedback.routes(), feedback.allowedMethods())
app.use(person.routes(), person.allowedMethods())
app.use(backFeedback.routes(), backFeedback.allowedMethods())
app.use(subscriber.routes(), subscriber.allowedMethods())
app.use(manager.routes(), manager.allowedMethods())
app.use(works.routes(), works.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
